package com.zzyl.nursing.service.impl;

import java.util.*;

import cn.hutool.core.collection.ListUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.IWechatService;
import com.zzyl.nursing.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 老人家属Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-02-24
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService
{
    @Autowired
    private FamilyMemberMapper familyMemberMapper;
    @Autowired
    private IWechatService wechatService;
    @Autowired
    private TokenService tokenService;


    static List<String> DEFAULT_NICKNAME_PREFIX = ListUtil.of("生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝"
    );

    /**
     * 查询老人家属
     * 
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id)
    {
        return getById(id);
    }

    //实例随机类
    private Random random = new Random();
    /**
     * 查询老人家属列表
     * 
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember)
    {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember)
    {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     * 
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember)
    {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     * 
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     * 
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 小程序登录
     *
     * @param userLoginRequestDto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //1.远程调用微信服务器登录认证接口获取openid
        String openId = wechatService.getOpenId(userLoginRequestDto.getCode());

        //2.根据openid查询数据库用户FamilyMember
        LambdaQueryWrapper<FamilyMember> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(FamilyMember::getOpenId,openId);
        FamilyMember member = getOne(queryWrapper);

        //3.如果获取用户无效，自己实例用户对象FamilyMember封装openId
        if(member==null){
            member = FamilyMember.builder().openId(openId).build();
        }
        //4.远程调用微信服务器获取手机号接口获取手机号
        String phoneNumber = wechatService.getPhoneNumber(userLoginRequestDto.getPhoneCode());

        //5.新增或更新用户对象FamilyMember数据
        if(member.getId()==null){
            //执行新增操作
            member.setPhone(phoneNumber);//设置手机号
            //设置随机的昵称（用户第一次来到我们小程序注册的事后设置唯一昵称）
            //   规则名称：随机list集合一个元素+手机号后4位
            member.setName(DEFAULT_NICKNAME_PREFIX.get(random.nextInt(DEFAULT_NICKNAME_PREFIX.size()))+
                    phoneNumber.substring(phoneNumber.length()-4));
            //插入数据库
            save(member);

        }else if(!member.getPhone().equals(phoneNumber)){
            //当前用户id有值，执行更新操作
            //注意：获取的最新手机号phoneNumber和数据库中存储当前用户手机号member.getPhone()不一样才需要更新
            member.setPhone(phoneNumber);//更新手机号
            //更新数据库操作
            updateById(member);
        }

        //6.生产token
        Map<String,Object> claims = new HashMap<>();
        claims.put("userId", member.getId());
        claims.put("nickName", member.getName());
        String token = tokenService.createToken(claims);

        //7.封装LoginVo返回数据
        return LoginVo.builder()
                .token(token)
                .nickName(member.getName())
                .build();
    }
}
